package com.reggie.console.controller;


import com.reggie.acl.dataobject.User;
import com.reggie.common.enums.ResponseCode;
import com.reggie.common.exception.ReggieException;
import com.reggie.common.util.ReggieContext;
import com.reggie.console.annotation.AuthRule;
import com.reggie.console.dto.ResultDTO;
import com.reggie.console.enums.ReggieRole;
import com.reggie.console.util.ResultBuilder;
import com.reggie.service.facade.ShortMessageFacade;
import com.reggie.service.model.request.UserLoginRequest;
import com.reggie.service.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author yth
 * @since 2023-02-04
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    private static final String USER_SESSION_KEY = "user";

    @Autowired
    private UserService userService;

    @Autowired
    private ShortMessageFacade shortMessageFacade;

    /**
     * 用户登入功能
     * 发送短信验证码
     *
     * @param user 封装了手机号码数据
     */
    @PostMapping("/sendMsg")
    public ResultDTO<String> sendMsg(@RequestBody User user) {
        log.info("sendMsg()");
        String phoneNum = user.getPhone();
        if (StringUtils.isBlank(phoneNum)) {
            throw new ReggieException(ResponseCode.CLIENT_ERROR, "手机号码为空，非法操作");
        }
        shortMessageFacade.sendSMValidateCode(phoneNum);
        return ResultBuilder.ok("手机短信验证码发送成功，请在60秒内验证");
    }

    /**
     * 登入
     *
     * @param map     用户手机号码和验证码
     * @param session session
     * @return 登入用户数据
     */
    @PostMapping("/login")
    public ResultDTO<User> login(@RequestBody UserLoginRequest request, HttpSession session) {
        // 登入成功
        User loginUser = userService.login(request);
        session.setAttribute(USER_SESSION_KEY, loginUser.getId());
        return ResultBuilder.ok(loginUser);
    }

    /**
     * 退出登入
     *
     * @param session session
     * @return 信息
     */
    @PostMapping("/logout")
    @AuthRule(roles = {ReggieRole.CUSTOMER})
    public ResultDTO<String> logout(HttpSession session) {
        log.info("{} logout ...", ReggieContext.getInstance().getUserId());
        session.removeAttribute(USER_SESSION_KEY);
        return ResultBuilder.ok("退出登入成功");
    }
}

